var currUser = "";
var currSessioncode = "";

// 左侧菜单栏点击事件
function menuLink(url){  
    var frameid = document.getElementById("rightbottom");  
    frameid.src = url;
} 
var initMainPage = function()
{
	var menus;	
	var left_menu_json = {
		"productName":"CDN监控系统",
		"menu":
		[
			{
				"index":"0",
				"label":"cdn_main_menu_business",
				"icon":"icon-folder-close",
				"submenu":
				[
					{
						"label":"cdn_main_menu_bus_chl",
						"href":"/iui/business/html/channles.html"
					},
					{
						"label":"cdn_main_menu_bus_node",
						"href":"/iui/business/html/nodes.html"
					}
					,
					{
						"label":"cdn_main_menu_bus_subnode",
						"href":"/iui/business/html/subnode.html"
					},
					{
						"label":"cdn_main_menu_bus_citask",
						"href":"/iui/business/html/citask.html"
					},
					{
						"label":"cdn_main_menu_bus_task_dis",
						"href":"/iui/business/html/taskdis.html"
					},
					{
						"label":"cdn_main_menu_bus_file",
						"href":"/iui/business/html/file.html"
					}
					,
					{
						"label":"cdn_main_menu_bus_file_info",
						"href":"/iui/business/html/fileinfo.html"
					}
				]
			
			},
			{
				"index":"1",
				"label":"cdn_main_menu_sysmonitor",
				"icon":"icon-tasks",
				"submenu":
				[
					{
						"label":"cdn_main_menu_sysmonitor_service",
						"href":"/iui/business/html/sysmonitor.html"
					}
//					,
//					{
//						"label":"cdn_main_menu_sysmonitor_alarm",
//						"href":"/iui/business/html/alarm.html"
//					}
				]
			},
			{
				"index":"4",
				"label":"cdn_main_menu_alarm",
				"icon":"icon-info-sign",
				"submenu":
				[
					{
						"label":"cdn_main_menu_active_alarm",
						"href":"/iui/business/html/alarm.html"
					},
					{
						"label":"cdn_main_menu_history_alarm",
						"href":"/iui/business/html/historyalarm.html"
					}
				]
			},
			{
				"index":"2",
				"label":"cdn_main_menu_config",
				"icon":"icon-cog",
				"submenu":
				[
					{
						"label":"cdn_main_menu_config_para",
						"href":"/iui/business/html/config.html"
					}
//					,
//					{
//						"label":"rtms_main_menu_dg_device_manger",
//						"href":"/iui/diagnosis/html/reset_reboot.html"
//					}
				]
			},
			{
				"index":"3",
				"label":"cdn_main_menu_usmc",
				"icon":"icon-lock",
				"submenu":
				[
					{
						"label":"cdn_main_menu_usmc_usermg",
						"href":"/iui/security/html/userManager.html"
					}
				/* 	{
						"label":"rtms_main_menu_usmc_passmdy",
						"href":"/iui/security/html/modifyPassword.html"
					} */
				]
			
			}
		]
	};
	menus = left_menu_json.menu;	
	
	// add product name
	//$("#logoText").text(left_menu_json.productName);
	
	var firstMenu_end = "</div>";
	
	var menu = "<div id='{label}' class='nav-panel firstMenu'><span id='{icon}'></span>";
	
	var submenu = "<div id='{label}' class='my_menu_item nav-item' name_i18n='rtms_framework_ui_i18n' " +
			          "onclick='addItemToTab(\"{url}\",this);'>" +
			      "</div>";
	
	var menuCount = menus.length;
	for ( var i = 0; i < menuCount; ++i)
	{
		var subCount = menus[i].submenu.length;
		var temp = "";
		temp = menu.replace("{icon}", menus[i].icon).replace("{label}", menus[i].label);
		
		for ( var j = 0; j < subCount; j++)
		{
			temp = temp
					+ submenu.replace("{url}", menus[i].submenu[j].href).replace("{label}", menus[i].submenu[j].label);
		}
		
		temp = temp + firstMenu_end;
		$("#leftmenu").append(temp);
	}
	
	// 国际化
	//loadPropertiesMainMenu();
	
};


// 鼠标移入移出时改变图片的样式
function changeHeaderImg() 
{
	var oLi = $(".right_imgs_css");
	for (var i = 0; i < oLi.length; i++) 
	{
		oLi[i].onmouseover = function() 
		{
			$(this).addClass("header_alpha");
		};
		oLi[i].onmouseout = function() 
		{
			$(this).removeClass("header_alpha");
		};
	}
}

// 单击菜单项时，增加一个tabpanel
function addItemToTab(url, obj) 
{
	var urltemp = url.split("/");
	var tabidtemp = urltemp[urltemp.length - 1].split(".");
	var tabid = tabidtemp[0];
	
	var count = $('#tabs').omTabs('getLength');
	if($("a[tabId='" + tabid + "']").length <= 0 && count > 20)
	{
		$.omMessageBox.alert(
		{
			type : 'warning',
			title : i18n.prop('alert'),
			content : i18n.prop('tabMaxConut')
		});
		return;
	}
	
	if ($("a[tabId='" + tabid + "']").length > 0) 
	{
		$('#tabs').omTabs('activate', tabid);
	} 
	else 
	{
		$('#tabs').omTabs('add', 
		{
			tabId : tabid,
			title : obj.innerHTML,
			closable : true,
			tabMenu : true,
			border : false,
			content : "<iframe src ='" + url + "' id='" + tabid + "' name='" + tabid
					+ "'  marginwidth=0 style='overflow:hidden;' marginheight=0 width=100% height='' " 
					+ " frameborder='no' border=0 ></iframe>"
		});
		
		contents = "<iframe src ='" + url + "' id='" + tabid + "' name='" + tabid
		+ "'  marginwidth=0 style='overflow:hidden;' marginheight=0 width=100% height='' " 
		+ " frameborder='no' border=0 ></iframe>";
		
	}
}

// 设置iframe的高度（目前只考虑ff） 用name属性，可兼容所有浏览器
function setIframeHeight(iframe_id, iframe_height) 
{
	document.getElementById(iframe_id).height = iframe_height;
}

// 获取cookie
function getCookie(cname) {
	var name = cname + "=";
	var ca = document.cookie.split(';');
	for(var i=0; i<ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1);
		if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
	}
return "";
}

$(document).ready(function()
{
	loadPropertiesMainMenu();
	$('#confTab').text(i18n.prop('OMC'));
	$('#firstTab').text(i18n.prop('firstTab'));
	$('#com_raisecom_itms_usmc_oldpasswd').text(main_i18n.prop('com_raisecom_itms_usmc_oldpasswd') + i18n.prop('colon'));
	$('#com_raisecom_itms_usmc_newpasswd').text(main_i18n.prop('com_raisecom_itms_usmc_newpasswd') + i18n.prop('colon'));
	$('#com_raisecom_itms_usmc_cfnewpasswd').text(main_i18n.prop('com_raisecom_itms_usmc_cfnewpasswd') + i18n.prop('colon'));
	//$('#com_raisecom_itms_usmc_passwdStrong').text(main_i18n.prop('com_raisecom_itms_usmc_passwdStrong') + i18n.prop('colon'));
	
	// init set left menu overflow
	//$("#main-nav .navigation").css("overflow", "auto");
	$.ajax(
	{
		url : FrameConst.REST_GET_USERNAME,
		type : "GET",
		cache : false,
		contentType : 'application/json; charset=utf-8',
		success : function(data)
		{
			var userName = data;
			currUser = userName;
			currSessioncode = getCookie('sessioncode');
			$("#curr_user").text(main_i18n.prop("rtms_main_curr_user").replace("{user}", userName));
		}
	});
	
	// 定义用户登出事件
	window.doLogout = function()
	{
		$.ajax(
		{
			url : FrameConst.REST_LOGOUT,
			type : "GET",
			cache : false,
			contentType : 'application/json; charset=utf-8',
			success : function(data)
			{
				if (0 == data.result)
				{
					window.location = FrameConst.DEFAULT_LOGIN_PAGE;
				}
			}
		});
	};
	
	// 绑定用户登出事件
	$("#logout").click(function()
	{
		// if (window.confirm(main_i18n.prop("rtms_main_cf_logout"))) doLogout();
		$.omMessageBox.confirm({
			type:'confirm',
			content: main_i18n.prop("rtms_main_cf_logout"),
			onClose:function(value){
				if(value)
				{
					doLogout();
				}
            }
        });
	});
	
	// 绑定版本信息显示事件
	$("#version").click(function()
	{
		$.omMessageBox.alert({
			type:'alert',
			content: main_i18n.prop("rtms_main_cf_version"),
        });
	});
	
	// 回到主页
	$("#to_home").click(function()
	{
		$('#tabs').omTabs('activate', "firstTab");
	});
	
	// 刷新
	/*$("#refresh_page").click(function()
	{
		goToHome();
	});*/
	
	// 回到首页
	var goToHome = function()
	{
		// 关闭其它页签，刷新首页页签
		var self = tabs, $headers = self.find('>div.om-tabs-headers');

		$headers.find('ul li').each(function(index, item) 
		{
			var itemId = $(item).find('a.om-tabs-inner').attr('tabid');
			if ("firstTab" === itemId)
			{
				return;
			}
			self.omTabs('close', (self.omTabs('getAlter', itemId)));
		});
	};
	
	// 修改密码弹出框
	var dialogPass = $("#update_pwd_dialog-modal").omDialog(
	{
		autoOpen: false,
		height: 240,
		modal: true,
		width: 500,
		resizable : false,
		onClose : function(event)
		{
			// 清除红框样式
			$("input").removeClass("x-form-invalid");
		}
	});
	
	// 弹出框提交按钮
	$('#passSubmit').click(function()
	{
		modifyPasswdSubmit();
		return false;
	});
	
	// 弹出框取消按钮
	$('#passCancel').click(function()
	{
		$("#update_pwd_dialog-modal").omDialog("close");
		
		// 清除红框样式
		$("input").removeClass("x-form-invalid");
		return false;
	});
	
	// 修改密码按钮
	$("#set_user").click(function()
	{
		// 恢复Form到验证前的状态
		validator.resetForm();
		$('#passSubmit').text(i18n.prop('btnDiaSubmit'));
		$('#passCancel').text(i18n.prop('btnDiaCancel'));
		$("#update_pwd_dialog-modal").show();
		dialogPass.omDialog("option", "title", i18n.prop('updatePwdTitle'));
		dialogPass.omDialog('open');
	});
	
	// 用户心跳事件，查询session是否过期
	var heart = setInterval(function()
	{
	    if(getCookie('sessioncode') != "")
        {	
            $.ajax(
			{
				url : FrameConst.REST_GET_USERNAME,
				type : "GET",
				cache : false,
				contentType : 'application/json; charset=utf-8',
				success : function(data)
				{
					var userName = data;
					if (userName == null || userName == undefined || userName == '')
					{
						window.location = FrameConst.DEFAULT_LOGIN_PAGE+'?'+Math.random();
					}
				}
			});
         }
         else
         {
                var expireTime = new Date().getTime() + 1000*36000;
                var da=new Date();
                da.setTime(expireTime);
                document.cookie = 'sessioncode='+currSessioncode+';expires='+da.toGMTString()+';path=/';
                document.cookie = 'username='+currUser+';expires='+da.toGMTString()+';path=/';
                doLogout();    
         }
	}, FrameConst.USER_HEART);
	
	// 父级菜单页签对象
	var allNeNum = 
	[
	 	'rtmsMenuPanel'
	];
	
	// 主界面布局
	var element = $('#page').omBorderLayout(
	{
		panels : 
		[
		 	{
				id : "north-panel",
				header : false,
				region : "north",
				height : 38
			},
			{
				id : "center-panel",
				header : false,
				region : "center"
			}, 
			{
				id : "west-panel",
				resizable : true,
				collapsible : true,
				title : i18n.prop('systemCatalog'),
				region : "west",
				width : 280
			}
		]

	});
	
	// 生成一级菜单
	$('.firstMenu').each(function() 
	{
		$("#" + $(this).attr('id')).omPanel(
		{
			title : main_i18n.prop($(this).attr('id')),//panel.title,
			icon : $(this).find("span").attr('id'),//panel.icon,
			collapsed : false,
			collapsible : true,

			// 面板收缩和展开的时候重新计算自定义滚动条是否显示
			onCollapse : function() 
			{
				$("#west-panel").omScrollbar("refresh");
			},
			onExpand : function() 
			{
				$("#west-panel").omScrollbar("refresh");
			}
		});
	});
	
	// 父级页签菜单
	var headTabs = $("#headTabs").omTabs(
	{
		width : '100%',
		height : '100%',
		closeFirst: false,
		closable : true,
		tabWidth : 80
	});
	
	// 功能页签
	var tabs = $("#tabs").omTabs(
	{
		width : '100%',
		height : '100%',
		tabMenu : true,
		closeFirst: false,
		closable : true,
		tabWidth : 100
	});

	// 系统配置单击事件
	$('#confTab').click(function()
	{
		showOrHideMenu('rtmsMenuPanel');
	});
	
	// 把首页的关闭图标去掉
	$('#headTabs').find('div ul li a').find('+ a.om-icon-close').remove();
	$("#firstTab").find("+ a.om-icon-close").remove();
    
	// 设置一级菜单样式
	$('.om-panel-header').css('height', '30px');
	$('#leftmenu .om-panel-title').css('margin-top', '10px');
	$('.om-icon').css('margin-top', '10px');
    
	// 设置菜单收起按钮样式
	$('.panel-tool-collapse').css('margin-top','3px');
	
	setIframeHeight("firstTab", 400);
});